<!--
 * @Descripttion: 
 * @Date: 2021-12-15 14:26:23
 * @LastEditTime: 2022-01-27 11:17:29
-->
<template>
  <div>
    {{$route.name}}
  </div>
</template>

<script>
export default {
  data () {
    return {
    }
  },
  components: {},
  created () {
    /*
 * @Descripttion:
 * @Date: 2022-01-26 15:22:48
 * @LastEditTime: 2022-01-26 15:46:30
 */
    let arr = [
      { id: 1, name: '部门1', pid: 0 },
      { id: 2, name: '部门2', pid: 1 },
      { id: 3, name: '部门3', pid: 1 },
      { id: 4, name: '部门4', pid: 3 },
      { id: 5, name: '部门5', pid: 4 },
    ]

    const getChildren = (data, result, pid) => {
      for (const item of data) {
        if (item.pid === pid) {
          const newItem = { ...item, children: [] }
          result.push(newItem)
          getChildren(data, newItem.children, item.id)
        }
      }
    }

    const arrayToTree = data => {
      let result = []
      getChildren(data, result, 0)
      return result
    }

    const arrtoTree = data => {
      const result = []
      const itemMap = {}
      for (const item of data) {
        const { id, pid } = item
        if (!itemMap[id]) {
          itemMap[id] = { children: [] }
        }
        itemMap[id] = {
          ...item,
          children: itemMap[id]['children']
        }

        const treeItem = itemMap[id]

        if (pid === 0) {
          result.push(treeItem)
        } else {
          if (!itemMap[pid]) {
            itemMap[pid] = {
              children: []
            }
          }
          itemMap[pid].children.push(treeItem)
        }
      }
      return result
    }

    console.log(arrtoTree(arr))

  },
  methods: {}
}
</script>

<style lang='scss' scoped>
</style>